﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace Headsight.BPMN2WF.Transformation.BPMN2TransformerMappings.Config
{
    public enum ConditionSource
    {
        FlowNode,
        TypeOfFlowElement
    }

    public class BPMN2WFTransformationConfigMaps
    {
        public IList<BPMN2WFTransformationConfigMap> ConfigMaps { get; private set; }
        public IBPMN2WFTransformation DefaultDestinationObject { get; private set; }

        public BPMN2WFTransformationConfigMaps()
        {
            ConfigMaps = new List<BPMN2WFTransformationConfigMap>();
        }

        public static BPMN2WFTransformationConfigMaps ReadConfigFromXml(XmlDocument xmlDoc)
        {
            var root = xmlDoc.DocumentElement;

            if (root != null)
            {
                var mappingsNode = root.SelectSingleNode("mappings");
                var result = new BPMN2WFTransformationConfigMaps();

                var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == mappingsNode.Attributes["assembly"].Value);
                var type = assembly.GetType(mappingsNode.Attributes["defaultType"].Value);
                var instance = Activator.CreateInstance(type) as IBPMN2WFTransformation;
                result.DefaultDestinationObject = instance;

                if (mappingsNode != null)
                {
                    foreach (XmlNode mappingNode in mappingsNode.ChildNodes)
                        result.ConfigMaps.Add(BPMN2WFTransformationConfigMap.FromXmlMappingNode(mappingNode));
                }

                return result;
            }
            return null;
        }

    }
}
